package com.repast.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.repast.common.Const;
import com.repast.common.ServerResponse;
import com.repast.dao.AddDishMapper;
import com.repast.dao.OrdersMapper;
import com.repast.pojo.AddDish;
import com.repast.pojo.Orders;
import com.repast.service.IAddDishService;
import com.repast.utils.DateUtils;
import com.repast.utils.PackagePayInfo;
import com.repast.vo.AddDishItemVo;
import com.repast.vo.AddDishOrders;
import com.repast.vo.PayMoneyInfo;

@Service
public class AddDishServiceImpl implements IAddDishService {

	@Autowired
	private AddDishMapper addDishMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	
	public ServerResponse addDish(AddDishOrders addDishOrders) throws Exception {
		// Orders orders =
		// ordersMapper.selectByPrimaryKey(addDishOrders.getOrdersId());
		List<AddDishItemVo> list = addDishOrders.getAddDishItemList();
		if (list.size() == 0) {
			return ServerResponse.createByErrorMessage("系统异常,没有添加加菜项!");
		}
		for (AddDishItemVo addDishItemVo : list) {
			AddDish addDish = new AddDish();
			addDish.setOrdersId(addDishOrders.getOrdersId());
			addDish.setFoodsId(addDishItemVo.getFoodsId());
			addDish.setAddDishNum(addDishItemVo.getAddDishItemNum());
			addDish.setAddDishSubtotal(addDishItemVo.getAddDishItemSubtotal());
			addDish.setAddDishStatus(Const.AddDishStatus.NO_RECEIVE);
			addDish.setAddDishCreateTime(DateUtils.formatDateTime(new Date(), "long"));
			addDish.setAddDishUpdateTime(DateUtils.formatDateTime(new Date(), "long"));
			int insert = addDishMapper.insert(addDish);
			if (insert == 0) {
				return ServerResponse.createByErrorMessage("加菜项,生成失败");
			}
		}
		Orders orders = ordersMapper.selectByPrimaryKey(addDishOrders.getOrdersId());
		PayMoneyInfo info = PackagePayInfo.packageMessage(orders.getOrdersNum(), orders.getOpenid(), addDishOrders.getAddDishTotal());
		return ServerResponse.createBySuccess(info);
	}

	public ServerResponse recountOrdersTotal(Integer ordersId, Double AddDishTotal) {
		Orders orders = ordersMapper.selectByPrimaryKey(ordersId);
		Double ordersTotal = orders.getOrdersTotal();
		ordersTotal+=AddDishTotal;
		orders.setOrdersTotal(ordersTotal);
		orders.setOrdersUpdateTime(DateUtils.formatDateTime(new Date(), "long"));
		int updateResult = ordersMapper.updateByPrimaryKeySelective(orders);
		if(updateResult==0){
			return ServerResponse.createByErrorMessage("系统异常,订单总额生成失败");
		}
		return ServerResponse.createBySuccess();
	}

}
